import React, { useState, useEffect, memo } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Typography, Input, Table, InputNumber, Popconfirm, Form } from 'antd';
import { Button, Space, Modal } from 'antd';
import {
  SearchOutlined,
  DeleteOutlined,
  FileAddOutlined,
  DownloadOutlined,
  UploadOutlined,
  EditOutlined,
  RedoOutlined,
} from '@ant-design/icons';
import '../warning/config';
import { connect } from 'dva';

const { Search } = Input;
const { Column } = Table;
const itemStyle = {
  margin: ' 0 0.5rem 0.6rem',
};

const formLayout = {
  labelCol: { xs: 4, sn: 4 },
  wrapperCol: { xs: 24, sm: 20 },
};
// const EditableCell = ({
//   editing,
//   dataIndex,
//   title,
//   inputType,
//   record,
//   index,
//   children,
//   ...restProps
// }) => {
//   const inputNode = inputType === 'number' ? <InputNumber /> : <Input />
//   return (
//     <td {...restProps}>
//       {editing ? (
//         <Form.Item
//           name={dataIndex}
//           style={{
//             margin: 0,
//           }}
//           rules={[
//             {
//               required: true,
//               message: `Please Input ${title}!`,
//             },
//           ]}
//         >
//           {inputNode}
//         </Form.Item>
//       ) : (
//         children
//       )}
//     </td>
//   )
// }

const Accident = (props) => {
  // 导出数据的输入框绑定数据
  const [value, setvalue] = useState('');
  // 当前行数据
  const [record, setrecord] = useState({
    accidentReason: '',
    damageCondition: '',
    occurrenceSite: '',
    vehicleId: '',
    accidentId: '',
  });
  // const [selectedRowKeys, setrowkeys] = useState([])
  const [type, settype] = useState(1);
  const [visible, setvisible] = useState(false);

  // const [editingKey, setEditingKey] = useState('')
  const { dispatch, accidentlist } = props;
  // const [data, setData] = useState(accidentlist)
  // const isEditing = record => record.key === editingKey
  // 操作数组
  const modalTitle = ['', '新增', '编辑'];
  // modal子组件  弹窗用于操作
  const CollectionCreateForm = memo(
    // 需要继承外部传来的属性和方法
    ({ visible, onCreate, onCancel, type, record }) => {
      //子组件   展开弹窗
      const [form] = Form.useForm();
      form.setFieldsValue(record);
      // 点击ok后 和外部onCreate一起执行的方法
      const onOK = () => {
        form
          .validateFields()
          .then((values) => {
            form.resetFields();
            onCreate(values, record.accidentId);
          })
          .catch((info) => {});
      };
      return (
        <Modal
          title={modalTitle[type]}
          onCancel={onCancel}
          onOk={onCreate}
          visible={visible}
          onOk={onOK}
        >
          <Form
            {...formLayout}
            // initialValues={records} 默认值，动态值用setFieldsValue
            form={form}
          >
            <Form.Item
              name="accidentReason"
              label="故障原因"
              rules={[{ required: true, message: '请输入故障原因' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="damageCondition"
              label="损坏情况"
              rules={[{ required: true, message: '请输入损坏情况' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="occurrenceSite"
              label="发生地点"
              rules={[{ required: true, message: '请输入发生地点' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="vehicleId"
              label="汽车编号"
              rules={[{ required: true, message: '请输入汽车编号' }]}
            >
              <Input />
            </Form.Item>
          </Form>
        </Modal>
      );
    },
  );
  // 点击ok确定后执行的方法
  const onCreate = (values) => {
    hiddenModal();
    if (type === 1) {
      // 添加条目
      dispatch({
        type: 'accidents/addRecord',
        payload: { ...values },
      });
    } else {
      // 更新条目
      dispatch({
        type: 'accidents/updateRecord',
        payload: { ...values, accidentId: record.accidentId },
      });
      // 重新获取一下 更新列表数据
      dispatch({
        type: 'accidents/getAllRecords',
      });
      console.log({ ...values, accidentId: record.accidentId });
    }
  };
  // 隐藏modal框
  const hiddenModal = () => {
    setvisible(false);
  };
  // 点击添加记录后执行的方法
  const add = () => {
    setvisible(true);
    settype(1);
    setrecord({
      accidentReason: '',
      damageCondition: '',
      occurrenceSite: '',
      vehicleId: '',
    });
  };
  // 删除条目
  const deleteOne = (record) => {
    dispatch({
      type: 'accidents/deleteRecord',
      payload: { id: record.accidentId },
    });
    console.log(record);
  };
  // 点击编辑后 然后启动modal框
  const edit = (record) => {
    setvisible(true);
    settype(2);
    setrecord(record);
    // console.log(record)
  };
  useEffect(() => {
    dispatch({
      type: 'accidents/getAllRecords',
    });
    // setData(accidentlist)
    return () => {};
  }, []);
  // 根据故障id搜索
  const onSearch = (value) => {
    if (value) {
      dispatch({
        type: 'accidents/getOneRecords',
        payload: { id: value },
      });
      // setData(accidentlist)
    } else {
      dispatch({
        type: 'accidents/getAllRecords',
        // payload: { id: value },
      });
      // setData(accidentlist)
    }
  };
  // 根据车辆编号搜索
  const onCarSearch = (value) => {
    if (value) {
      dispatch({
        type: 'accidents/getRecordByVehicleId',
        payload: { id: value },
      });
      // setData(accidentlist)
    }
  };

  const columns = [
    {
      title: '故障编号',
      dataIndex: 'accidentId',
      key: 'accidentId',
      editable: true,
    },
    {
      title: '车牌号',
      dataIndex: 'licenseNumber',
      key: 'accidentId',
      editable: true,
    },
    {
      title: '故障原因',
      dataIndex: 'accidentReason',
      key: 'accidentId',
      editable: true,
    },
    {
      title: '损坏情况',
      dataIndex: 'damageCondition',
      key: 'accidentId',
      editable: true,
    },
    {
      title: '发生地点',
      dataIndex: 'occurrenceSite',
      key: 'accidentId',
      editable: true,
    },
    {
      title: '发生时间',
      dataIndex: 'createTime',
      key: 'accidentId',
      // editable: true,
    },
    {
      title: '操作',
      render: (record) => {
        //
        return (
          <Space size="middle">
            <a onClick={() => edit(record)}>
              <EditOutlined /> 编辑
            </a>
            <a
              onClick={() => {
                deleteOne(record);
              }}
              className="ant-dropdown-link"
            >
              <DeleteOutlined /> 删除
            </a>
          </Space>
        );
      },
    },
  ];
  return (
    <PageContainer>
      <div style={{ width: '20%', float: 'right', marginBottom: '10px' }}>
        <Input
          placeholder="车辆id"
          style={{ display: 'inline-block', width: '65%' }}
          value={value}
          onChange={(e) => {
            setvalue(e.target.value);
          }}
        />

        {/* 导出数据 */}
        <Button
          type="primary"
          href={
            global.constants.url + '/accidentRecord/export?vehicleId=' + value
          }
          style={{
            display: 'inline-block',
            // marginLeft: '10px',
            float: 'right',
          }}
        >
          导出数据
        </Button>
      </div>

      <Search
        placeholder="输入故障编号"
        enterButton="查询"
        size="large"
        style={{ width: '79%', float: 'left', marginBottom: '10px' }}
        onSearch={onSearch}
      />
      <Search
        placeholder="输入车辆编号"
        enterButton="查询"
        size="large"
        style={{ width: '79%', float: 'left', marginBottom: '10px' }}
        onSearch={onCarSearch}
      />
      <Button
        onClick={add}
        type="primary"
        style={{
          marginBottom: 16,
          marginTop: '10px',
          marginLeft: '1%',
        }}
      >
        添加故障记录
      </Button>
      <Table
        bordered
        dataSource={accidentlist}
        columns={columns}
        rowClassName="editable-row"
        pagination={
          {
            // onChange: cancel,
          }
        }
      />
      {/* modal框组件 */}
      <CollectionCreateForm
        record={record}
        type={type}
        visible={visible}
        onCreate={onCreate}
        onCancel={hiddenModal}
      ></CollectionCreateForm>
    </PageContainer>
  );
};

export default connect(({ accidents: { accidentlist } }) => ({
  accidentlist,
}))(Accident);
